package admin

import (
	"fmt"
	"strconv"
	"encoding/json"
	"git.oschina.net/fuxiaohei/fuxiaohei-go.git/Core"
	"git.oschina.net/fuxiaohei/fuxiaohei-go.git/Rt"
)

// execute login action
func LoginDo(email string, password string) (userData map[string]string, valid string) {
	sql := Core.Sql("fuxiaohei_users", "id,user,password,email,real_name,role_name,status").Where("email = ?").Select()
	userData = Core.Db.One(sql, email)
	// check user data and access
	if len(userData) < 1 {
		valid = "用户不存在"
		return
	}
	if userData["role_name"] != "admin" {
		valid = "你没有权限"
		return
	}
	if userData["status"] != "active" {
		valid = "用户关闭中"
		return
	}
	// match password
	password = Rt.Crypto.Sha1Salt(password, Core.Config.String("salt.password"))
	if password != userData["password"] {
		valid = "密码错误"
		return
	}
	// do not return password column
	delete(userData, "password")
	return
}

// write session
func loginWriteSession(userData map[string]string, remember int, request *Core.HxRequest) (sessionData map[string]string) {
	sessionData = map[string]string{}
	// create session data
	sessionData["user_id"] = userData["id"]
	sessionData["token_value"] = Rt.Crypto.Sha1Salt(fmt.Sprint(Rt.Time.Now()) + userData["email"], Core.Config.String("salt.session"))
	sessionData["expire_time"] = fmt.Sprint(Rt.Time.Now() + remember*24*3600)
	// create session extra data
	extraData := map[string]string{}
	extraData["ip"] = request.Ip()
	extraData["user_agent"] = request.UserAgent()
	extraData["add_time"] = fmt.Sprint(Rt.Time.Now())
	tmpBytes, _ := json.Marshal(extraData)
	sessionData["data"] = string(tmpBytes)
	// write session
	sql := Core.Sql("fuxiaohei_sessions", "user_id,token_value,expire_time,data").Insert()
	Core.Db.Exec(sql, sessionData["user_id"], sessionData["token_value"], sessionData["expire_time"], sessionData["data"])
	return
}

// check session
func LoginCheck(request *Core.HxRequest) bool {
	// get user session info
	userId, token := request.Cookie("user_id"), request.Cookie("user_token")
	sql := Core.Sql("fuxiaohei_sessions").Where("user_id = ?").Where("token_value = ?").Select()
	sessionData := Core.Db.One(sql, userId, token)
	// check exist
	if len(sessionData) < 1 {
		return false
	}
	// check expire time
	expireTime, _ := strconv.ParseInt(sessionData["expire_time"], 10, 64)
	if int(expireTime) < Rt.Time.Now() {
		return false
	}
	return true
}

// destroy session
func LoginDestroy(response *Core.HxResponse) {
	response.Cookie("user_id", "", -100)
	response.Cookie("user_token", "", -100)
	response.Redirect("/login")
}
